﻿#include "qmpsw.h"
#include "ui_qmpsw.h"
#include "qlogin.h"
#include <QFile>
#include <QMessageBox>
extern std::map <QString,QString> UserInfo;
extern std::map <QString,QString> Usertype;//账户标志
extern QString defalut_account;
Qmpsw::Qmpsw(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Qmpsw)
{
    ui->setupUi(this);
    this->setWindowTitle(QString::fromLocal8Bit("密码修改"));
    setWindowFlags(Qt::Dialog |Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint|Qt::WindowTitleHint);
    ui->lineEdit_passwordold->setEchoMode(QLineEdit::Password);
    ui->lineEdit_passwordnew->setEchoMode(QLineEdit::Password);
    ui->lineEdit_passwordnew_2->setEchoMode(QLineEdit::Password);
    //ui->lineEdit_login->setText("admin");
    if (!this->isVisible())
    {
        setVisible(true);
    }
    setAutoFillBackground(true);
    this->setAttribute (Qt::WA_DeleteOnClose);
}

Qmpsw::~Qmpsw()
{
    delete ui;
}

QString Qmpsw::encryption(QString &str){
    //转码
    QByteArray ba;
    ba = str.toLatin1();
    QByteArray hexed = ba.toBase64();
    str = hexed.data();
    return str;
}

QString Qmpsw::Decrypt(QString &str){
    //解码
    QByteArray ba;
    ba = str.toLatin1();
    QByteArray hexed = QByteArray::fromBase64(ba);
    str = hexed.data();
    return str;
}

void Qmpsw::fun_writeUserInfo(){
    QFile file("resource/info.txt");
    file.open(QIODevice::WriteOnly| QIODevice::Text );
    QString sdefalut = defalut_account;
    file.write(encryption(sdefalut).toUtf8()+'\n');
    for (std::map<QString,QString>::iterator it = UserInfo.begin(); it!=UserInfo.end(); ++it)
    {
        QString str = it->first;
        file.write(encryption(str).toUtf8()+'\n');
        QString str1 = it->second;
        file.write(encryption(str1).toUtf8()+'\n');
        QString str2 = Usertype[it->first];
        file.write(encryption(str2).toUtf8()+'\n');
    }
    file.close();
}

void Qmpsw::on_Buttonsave_clicked()
{
    QString account = ui->lineEdit_login->text();
    QString pw_old = ui->lineEdit_passwordold->text();
    QString pw_new = ui->lineEdit_passwordnew->text();
    QString pw_new2 = ui->lineEdit_passwordnew_2->text();
    if(pw_new!=pw_new2){
        QMessageBox::information(this,QString::fromLocal8Bit("提示"),QString::fromLocal8Bit("两次密码输入不一致"));
        return;
    }
    std::map<QString,QString>::iterator it;
    it  =  UserInfo.find(account);
    if (it != UserInfo.end()){
        if(it->second == pw_old)
        {

            UserInfo[account]=pw_new;
            fun_writeUserInfo();
            this->accept();
        }else {

            QMessageBox::warning(this,QString::fromLocal8Bit("警告"),QString::fromLocal8Bit("密码错误"));

        }
    }


}

void Qmpsw::on_Button_cancel_clicked()
{
    this->reject();
}
